package cube.utils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cube.data.util.DataUtil;

/**
 * 字符处理工具
 * 
 * @author abiao
 */
public class StringUtil {

	/**
	 * 格式化输出多行字符串
	 */
	public static String format(String[] strs) {
		StringBuffer sb = new StringBuffer();
		sb.append("-----------------------");
		for (int i = 0; i < strs.length; i++) {
			sb.append("\n    " + strs[i]);
		}
		sb.append("\n");
		return sb.toString();
	}

	/**
	 * 检查字符是否为空
	 */
	public static boolean isBlank(String str) {
		return str == null || str.trim().equals("");
	}

	/**
	 * 删除字符中空格
	 */
	public static String deleteWhiteSpace(String str) {
		return removeAll(str, ' ');
	}

	/**
	 * 不够指定size时字符串前添加占位符
	 */
	public static String addOccupy(char occupy, String v, int size) {
		return copyDupChars(occupy, size - v.length()) + v;
	}

	/**
	 * 不够指定size时字符串后添加占位符
	 */
	public static String addOccupy(String v, int size, char occupy) {
		return v + copyDupChars(occupy, size - v.length());
	}

	/**
	 * 删除占位符
	 */
	public static String removeAll(String s, char c) {
		if (s == null) {
			return null;
		}
		return s.replaceAll(String.valueOf(c), "");
	}

	/**
	 * 分割字符串，包含分隔符
	 */
	public static String[] split(String s, String reg) {
		Matcher m = Pattern.compile(reg).matcher(s);
		List<String> matchList = new ArrayList<String>();
		int index = 0;
		while (m.find()) {
			String match = s.substring(index, m.start());
			if (!"".equals(match)) {
				matchList.add(match);
			}
			matchList.add(m.group());
			index = m.end();
		}
		if (index < s.length()) {
			matchList.add(s.substring(index));
		}
		return list2Array(matchList);
	}

	/**
	 * 删除空元素
	 */
	public static String[] removeEmptyElems(String[] ss) {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < ss.length; i++) {
			if (!"".equals(ss[i])) {
				list.add(ss[i]);
			}
		}
		return list2Array(list);
	}

	/**
	 * 检查是否为数字
	 */
	public static boolean isNumeric(String str) {
		if (str == null) {
			return false;
		}
		return str.trim().matches("[0-9]+");
	}

	/**
	 * 查找索引
	 */
	public static int indexOf(String str, String subStr) {
		if (str == null || subStr == null) {
			return -1;
		}
		return str.indexOf(subStr);
	}

	/**
	 * 获取指定字符集字符
	 */
	public static String getString(byte[] bytes, String charset) {
		String s = null;
		try {
			s = new String(bytes, charset);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return s;
	}

	/**
	 * 字符转为字节数组
	 */
	public static byte[] getBytes(char c) {
		return String.valueOf(c).getBytes();
	}

	/**
	 * 获取指定字符集字节码
	 */
	public static byte[] getBytes(String s, String charset) {
		byte[] bs = null;
		try {
			bs = s.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return bs;
	}

	/**
	 * 对字符串数组中的元素进行模糊查询过滤
	 */
	public static String[] filterStrings(String[] strs, String... filterStrs) {
		if (filterStrs == null) {
			return strs;
		}

		List<String> strList = new ArrayList<String>();
		for (int i = 0; i < strs.length; i++) {
			if (isFitFilters(strs[i], filterStrs)) {
				strList.add(strs[i]);
			}
		}
		return StringUtil.collection2Array(strList);
	}

	/**
	 * 是否匹配过滤器
	 */
	public static boolean isFitFilters(String str, String... filterStrs) {
		for (int i = 0; i < filterStrs.length; i++) {
			if (!str.contains(filterStrs[i])) {
				return false;
			}
		}
		return true;
	}

	/**
	 * String集合转为String数组
	 */
	public static String[] collection2Array(Collection<String> c) {
		String[] array = new String[c.size()];
		c.toArray(array);
		return array;
	}

	/**
	 * String数组去重
	 */
	public static String[] unique(String[] strs) {
		Set<String> set = new HashSet<String>();
		for (int i = 0; i < strs.length; i++) {
			set.add(strs[i]);
		}
		return StringUtil.collection2Array(set);
	}

	/**
	 * 判断是否为数字
	 */
	public static boolean isNum(char c) {
		return c >= '0' && c <= '9';
	}

	/**
	 * 获取字符串开头的数字
	 */
	public static String getHeadNum(String str) {
		int pos = 0;
		for (int i = 0; i < str.length(); i++) {
			if (!isNum(str.charAt(i))) {
				break;
			}
			pos = i + 1;
		}
		return str.substring(0, pos);
	}

	/**
	 * 获取由size个相同字符c组成的字符串
	 */
	public static String copyDupChars(char c, int size) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < size; i++) {
			sb.append(c);
		}
		return sb.toString();
	}

	/**
	 * 字符串列表转为字符串数组
	 */
	public static String[] list2Array(List<String> list) {
		return list.toArray(new String[list.size()]);
	}

	/**
	 * 字符s和strings中的莫个相同
	 */
	public static boolean inStrings(String s, String... strings) {
		for (int i = 0; i < strings.length; i++) {
			if (s.equals(strings[i])) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 砍掉字符串的尾部
	 */
	public static String cutTail(String s, String tail) {
		if (!s.endsWith(tail)) {
			return s;
		}
		return s.substring(0, s.lastIndexOf(tail));
	}

	/**
	 * 砍掉字符串的头部
	 */
	public static String cutHead(String s, String head) {
		if (!s.startsWith(head)) {
			return s;
		}
		return s.substring(head.length());
	}

	/**
	 * 如果s和ss中的某个相同，返回true
	 */
	public static boolean equalsOne(String s, String... ss) {
		if (s != null) {
			for (int i = 0; i < ss.length; i++) {
				if (s.equals(ss[i])) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 判定字符串数组的index位和s相同
	 */
	public static boolean equals(String[] ss, int index, String s) {
		return ss != null && ss.length > index && ss[index].equals(s);
	}

	/**
	 * 字符串搜索
	 * 
	 * @param s
	 *            字符串
	 * @param reg
	 *            匹配正则
	 * @return 匹配结果
	 */
	public static String[] find(String s, String reg) {
		Matcher m = Pattern.compile(reg).matcher(s);
		List<String> matches = new ArrayList<String>();
		while (m.find()) {
			matches.add(m.group());
		}
		return list2Array(matches);
	}

	/**
	 * 字符串搜索
	 * 
	 * @param s
	 *            字符串
	 * @param left
	 *            左边字符串匹配正则
	 * @param reg
	 *            要搜索的字符串本身匹配正则
	 * @param right
	 *            右边字符串匹配正则
	 * @return 匹配结果
	 */
	public static String[] find(String s, String left, String reg, String right) {
		String regex = "(?<=" + left + ")" + reg + "?(?=" + right + ")";
		Matcher m = Pattern.compile(regex).matcher(s);
		List<String> matches = new ArrayList<String>();
		while (m.find()) {
			matches.add(m.group());
		}
		return list2Array(matches);
	}

	/**
	 * 随机选取字符串
	 */
	public static String random(String... ss) {
		return ss[DataUtil.random(0, ss.length)];
	}

	/**
	 * 替换多组字符串
	 */
	public static String replace(String s, Map<String, String> replaceList) {
		for (Map.Entry<String, String> e : replaceList.entrySet()) {
			s = s.replaceAll(e.getKey(), e.getValue());
		}
		return s;
	}
}
